/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.behavior;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.config.task.assignment.TaskAssigneeConfigImpl;
import com.je.bpm.core.model.task.KaiteRandomUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.delegate.TaskListener;
import com.je.bpm.engine.delegate.event.ActivitiEventDispatcher;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.el.ExpressionManager;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntityManager;
import com.je.bpm.engine.upcoming.UpcomingCommentInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 凯特随机用户任务活动行为
 */
public class KaiteRandomUserTaskActivityBehavior extends KaiteBaseUserTaskActivityBehavior {

    private static final Logger logger = LoggerFactory.getLogger(KaiteRandomUserTaskActivityBehavior.class);

    private KaiteRandomUserTask kaiteRandomUserTask;

    public KaiteRandomUserTaskActivityBehavior(KaiteRandomUserTask kaiteRandomUserTask) {
        this.kaiteRandomUserTask = kaiteRandomUserTask;
    }

    @Override
    public void execute(DelegateExecution execution) {
        CommandContext commandContext = Context.getCommandContext();
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();

        TaskEntity task = taskEntityManager.create();
        ExecutionEntity executionEntity = (ExecutionEntity) execution;
        task.setExecution(executionEntity);
        task.setTaskDefinitionKey(kaiteRandomUserTask.getId());

        task.setBusinessKey(executionEntity.getProcessInstanceBusinessKey());

        ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
        ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();

        BpmnModel bpmnModel = processEngineConfiguration.getRepositoryService().getBpmnModel(executionEntity.getProcessDefinitionId());
        FlowElement flowElement = bpmnModel.getFlowElement(kaiteRandomUserTask.getId());
        if (flowElement == null) {
            throw new ActivitiException("Can't find the flow element from the definition.");
        }

        KaiteRandomUserTask kaiteRandomUserTask = (KaiteRandomUserTask) flowElement;

        TaskAssigneeConfigImpl taskAssigneeConfig = kaiteRandomUserTask.getTaskAssigneeConfig();
        String activeTaskAssignee = "";


        String activeTaskName = kaiteRandomUserTask.getName();
        String activeTaskDescription = kaiteRandomUserTask.getDocumentation();

        //任务名称
        if (StringUtils.isNotEmpty(activeTaskName)) {
            String name;
            try {
                name = (String) expressionManager.createExpression(activeTaskName).getValue(execution);
            } catch (ActivitiException e) {
                name = activeTaskName;
                logger.warn("property not found in task name expression " + e.getMessage());
            }
            task.setName(name);
        }

        //任务描述
        if (StringUtils.isNotEmpty(activeTaskDescription)) {
            String description;
            try {
                description = (String) expressionManager.createExpression(activeTaskDescription).getValue(execution);
            } catch (ActivitiException e) {
                description = activeTaskDescription;
                logger.warn("property not found in task description expression " + e.getMessage());
            }
            task.setDescription(description);
        }

        task.setAppVersion(executionEntity.getProcessInstance().getAppVersion());
        taskEntityManager.insert(task, executionEntity);
        task.setVariablesLocal(calculateInputVariables(execution));
        String format = String.format(ASSIGNEE_VARIABLE, kaiteRandomUserTask.getId());
        //看是不是直送过来的,或者前端给点人员信息，如果是直接取变量中的人员信息，如果不是再进行随机节点人员算法计算 executionEntity.getVariable(kaiteRandomUserTask.getId(), String.class)
        String assigneeExpressionValue ="";
        try {
            assigneeExpressionValue = String.valueOf(expressionManager.createExpression(format).getValue(execution));
        } catch (ActivitiException e) {
            logger.warn("property not found in task description expression " + e.getMessage());
        }
        if (Strings.isNullOrEmpty(assigneeExpressionValue)
                || ("randomTeamUserUUID123456".equals(assigneeExpressionValue))) {
            //获取人员算法谁执行次数少选谁
            activeTaskAssignee = getRandomTaskUserIds(bpmnModel, flowElement, commandContext, taskAssigneeConfig, execution, task);
            Object upcomingInfoObj = Context.getCommandContext().getAttribute(UPCOMINGINFO);
            if (upcomingInfoObj != null && upcomingInfoObj instanceof UpcomingCommentInfoDTO) {
                UpcomingCommentInfoDTO upcomingCommentInfoDTO = (UpcomingCommentInfoDTO) upcomingInfoObj;
                if (upcomingCommentInfoDTO.getAssigneeJson() != null) {
                    JSONArray jsonArray = JSONArray.parseArray(upcomingCommentInfoDTO.getAssigneeJson());
                    JSONObject assigneeUserJsonObject = new JSONObject();
                    assigneeUserJsonObject.put("nodeId", kaiteRandomUserTask.getId());
                    assigneeUserJsonObject.put("nodeName", kaiteRandomUserTask.getName());
                    assigneeUserJsonObject.put("assignee", activeTaskAssignee);
                    assigneeUserJsonObject.put("assigneeName", "");
                    jsonArray.add(assigneeUserJsonObject);
                    upcomingCommentInfoDTO.setAssigneeJson(jsonArray.toJSONString());
                }
                Context.getCommandContext().addAttribute(UPCOMINGINFO, upcomingCommentInfoDTO);
            }
        } else {
            activeTaskAssignee = assigneeExpressionValue;
        }
        // Handling assignments need to be done after the task is inserted, to have an id
        //任务分配人员
        validatePersonnelClearance(activeTaskAssignee, bpmnModel, task.getTaskDefinitionKey());
        handleAssignments(taskEntityManager, activeTaskAssignee, null, task, expressionManager, execution);

        JSONObject variableObj = handleBaseUserTaskConfig(kaiteRandomUserTask, task, expressionManager, bpmnModel);
        task.setVariableLocal(TASK_GLOBAL_VAR, variableObj.toJSONString());

        boolean skipUserTask = false;
        if (variableObj.containsKey("skip") && variableObj.getBoolean("skip")) {
            skipUserTask = true;
            variableObj.remove("skip");
        } else {
            if (Context.getCommandContext().getAttribute(SUBMIT_IS_GATEWAY) == null) {
                //添加审批告知
                addApprovalNotice(commandContext, execution, task);
            }
            //计算跳过表达式
//            if (StringUtils.isNotEmpty(activeTaskSkipExpression)) {
//                Expression skipExpression = expressionManager.createExpression(activeTaskSkipExpression);
//                skipUserTask = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression) && SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression);
//            }
        }

        processEngineConfiguration.getListenerNotificationHelper().executeTaskListeners(task, TaskListener.EVENTNAME_CREATE);

        // All properties set, now fire events
        if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
            ActivitiEventDispatcher eventDispatcher = Context.getProcessEngineConfiguration().getEventDispatcher();
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task));
            if (task.getAssignee() != null) {
                eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
            }
        }


        addUpcomingInfo(bpmnModel, execution, task.getAssignee(), task, false);
        //自动传阅
        automaticCirculation(task, bpmnModel);
        if (skipUserTask) {
            taskEntityManager.deleteTask(task, null, false, false);
            leave(execution);
        }

    }
}
